package com.demo.controller;

import com.demo.HelloApplication;
import com.demo.model.Project;
import com.demo.model.Receiver;
import com.demo.util.ControllerManager;
import com.demo.util.EmailSender;
import com.demo.util.Tabs;
import com.demo.util.Validator;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;

import static com.demo.util.ControllerManager.leftController;

public class MainController implements Initializable {
    private static final Logger log = LogManager.getLogger(MainController.class);

    @FXML
    private TextField project_name;

    @FXML
    private TextField date; //截止日期

    @FXML
    private TextField time; //截止时间

    @FXML
    private TextField contact_name;

    @FXML
    private TextField contact_tel;

    @FXML
    private TextArea contact_address;

    @FXML
    private TextField ccAddresses; //邮件抄送

    @FXML
    private ListView<String> receiversList;

    @FXML
    private TextField vendorName;

    @FXML
    private TextField vendorEmail;

    private void setupTextListeners() {
        project_name.textProperty().addListener((observable, oldValue, newValue) -> project_name.setText(newValue.trim()));
        contact_name.textProperty().addListener((observable, oldValue, newValue) -> contact_name.setText(newValue.trim()));
        contact_tel.textProperty().addListener((observable, oldValue, newValue) -> contact_tel.setText(newValue.trim()));
        contact_address.textProperty().addListener((observable, oldValue, newValue) -> contact_address.setText(newValue.trim()));
        vendorName.textProperty().addListener((observable, oldValue, newValue) -> vendorName.setText(newValue.trim()));
        vendorEmail.textProperty().addListener((observable, oldValue, newValue) -> vendorEmail.setText(newValue.trim()));
        date.textProperty().addListener((observable, oldValue, newValue) -> date.setText(newValue.trim()));
        time.textProperty().addListener((observable, oldValue, newValue) -> time.setText(newValue.trim()));
        ccAddresses.textProperty().addListener((observable, oldValue, newValue) -> ccAddresses.setText(newValue.replace("，", ",").replace("、", ",").trim()));
    }

    @FXML
    private Label alterLabel;

    @FXML
    private Label fileName;

    @FXML
    private AnchorPane ap;

    private Project project;
    private ArrayList<Receiver> receivers;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        this.receivers = new ArrayList<>();
        this.project = new Project();
        ControllerManager.mainController = this;
        setupTextListeners();
    }

    public void test(Project project, List<Receiver> receivers) {
        // 测试初始化
        project_name.setText(project.getProject_name());
        date.setText(project.getDate());
        time.setText(project.getTime());
        contact_name.setText(project.getContact_name());
        contact_tel.setText(project.getContact_tel());
        contact_address.setText(project.getContact_address());
        ccAddresses.setText(project.getCcAddresses());
        for (Receiver receiver : receivers) {
            receiversList.getItems().add(receiver.getCompany_name() + "," + receiver.getEmail());
            this.receivers.add(receiver);
        }
    }

    @FXML
    protected boolean checkProjectClick() {
        alterLabel.setText("");
        if (!Validator.isNotNull(project_name.getText())) {
            alterLabel.setText("项目名称有误！");
            return false;
        }
        if (!Validator.isNotNull(contact_name.getText())) {
            alterLabel.setText("联系人有误！");
            return false;
        }
        if (!Validator.isNotNull(contact_tel.getText())) {
            alterLabel.setText("联系电话有误！");
            return false;
        }
        if (!Validator.isNotNull(date.getText())) {
            alterLabel.setText("截止日期有误！");
            return false;
        }
        if (!Validator.isNotNull(time.getText())) {
            alterLabel.setText("截止时间有误！");
            return false;
        }
        if (!Validator.isNotNull(contact_address.getText())) {
            alterLabel.setText("邮寄地址有误！");
            return false;
        }
        if (!Validator.CheckccAddr(ccAddresses.getText())) {
            alterLabel.setText("抄送地址有误！");
            return false;
        }
        if (!Validator.isNotNull(fileName.getText())) {
            alterLabel.setText("缺少附件！");
            // 弹出提示框，提示用户上传附件
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("缺少附件");
            alert.setHeaderText("您尚未上传附件");
            alert.setContentText("是否继续？");

            Optional<ButtonType> result = alert.showAndWait();
            if (result.isPresent() && result.get() == ButtonType.OK) {
                ; // 继续
            } else {
                return false;
            }

        }

        // check通过 赋值 焦点下移
        this.project.setProject_name(project_name.getText());
        this.project.setDate(date.getText());
        this.project.setTime(time.getText());
        this.project.setContact_name(contact_name.getText());
        this.project.setContact_tel(contact_tel.getText());
        this.project.setContact_address(contact_address.getText());
        this.project.setCcAddresses(ccAddresses.getText());

        alterLabel.setText("ok");
        vendorName.requestFocus();
        return true;
    }

    @FXML
    protected void uploadButtonClick() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("Open Resource File");
        Stage stage = (Stage) ap.getScene().getWindow();
        File attachmentfile = fileChooser.showOpenDialog(stage);
        if (attachmentfile == null) {
            return;
        }
        this.fileName.setText(attachmentfile.getName());
        this.project.setAttachmentFile(attachmentfile);
        log.info("文件上传成功：{}", attachmentfile.getName());
    }

    @FXML
    protected void onDeleteReceiverClick() {
        int selectedIndex = receiversList.getSelectionModel().getSelectedIndex();
        if (selectedIndex >= 0) {
            receiversList.getItems().remove(selectedIndex);
            receivers.remove(selectedIndex);
        } else {
            alterLabel.setText("请选择要删除的项！");
        }
    }

    @FXML
    protected void onAddButtonClick() {
        if (!Validator.isNotNull(vendorName.getText())) {
            alterLabel.setText("供应商名称有误！");
            return;
        }
        if (!Validator.isEmail(vendorEmail.getText())) {
            alterLabel.setText("供应商邮箱有误！");
            return;
        }

        receiversList.getItems().add(vendorName.getText() + "," + vendorEmail.getText());

        Receiver receiver = new Receiver(vendorName.getText(), vendorEmail.getText());
        this.receivers.add(receiver);

        vendorName.setText("");
        vendorEmail.setText("");
    }

    @FXML
    protected void onNextStepClick() throws IOException {
        if (!checkProjectClick()) {
            return;
        }

        if (this.project == null) {
            alterLabel.setText("项目信息为空");
            return;
        }

        if (!(vendorName.getText().isEmpty() && vendorEmail.getText().isEmpty())) {
            alterLabel.setText("请先点击添加按钮");
            return;
        }

        if (this.receivers == null) {
            alterLabel.setText("供应商信息为空");
            return;
        }

        System.out.println("project:" + project.toString());
        for (Receiver receiver : receivers)
            System.out.println(receiver.toString());

        EmailSender.createEmail(project, receivers);

        // 切换下一页
        // 创建step2
        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("step2-view.fxml"));
        Scene newScene = new Scene(fxmlLoader.load());
        Tabs.addScene(Tabs.STEP2_KEY, newScene);
        leftController.setCurrentStep(2);

        Stage stage = (Stage) ap.getScene().getWindow();
        stage.setTitle("Step2!");
        stage.setScene(newScene);
        stage.show();
    }

    @FXML
    public void onCloseClick() {
        System.out.println("Main onCloseClick");
        Platform.exit();
        System.exit(0);
    }

}
